package com.cqc.jdk8.Jtext;

import org.junit.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.FieldPosition;
import java.text.NumberFormat;

public class NumberFormatTest {

    /**
     * Number
     */
    @Test
    public void number() {
        NumberFormat numberFormat = DecimalFormat.getNumberInstance();
        //小数位数
        numberFormat.setMaximumFractionDigits(5);
        String r1 = numberFormat.format(5 / 3f);//1.66667
        System.out.println(r1);

        NumberFormat numberFormat2 = NumberFormat.getNumberInstance();
        numberFormat2.setMaximumFractionDigits(5);
        String r2 = numberFormat.format(5 / 3f);//1.66667
        System.out.println(r2);


        NumberFormat numberFormat3 = NumberFormat.getInstance();
        numberFormat3.setGroupingUsed(false);
        StringBuffer stringBuffer = new StringBuffer();
        FieldPosition fieldPosition = new FieldPosition(NumberFormat.FRACTION_FIELD);
        stringBuffer = numberFormat3.format(1234.56789, stringBuffer, fieldPosition);
        System.out.println(stringBuffer.toString());//1234.568 format()默认3位？
        //field=1=NumberFormat.FRACTION_FIELD,beginIndex=5,endIndex=8
        int field = fieldPosition.getField();
        int beginIndex = fieldPosition.getBeginIndex();
        int endIndex = fieldPosition.getEndIndex();
        System.out.println("field=" + field + ",beginIndex=" + beginIndex + ",endIndex=" + endIndex);
    }

    /**
     * Currency  金额
     */
    @Test
    public void currency() {
        NumberFormat currencyFmt = NumberFormat.getCurrencyInstance();
        String format = currencyFmt.format(100.56);
        System.out.println(format);//￥100.56

    }

    /**
     * percent 百分比
     */
    @Test
    public void percent() {
        NumberFormat percentFmt = NumberFormat.getPercentInstance();
        percentFmt.setMaximumFractionDigits(2);
        percentFmt.setMinimumFractionDigits(2);
        percentFmt.setRoundingMode(RoundingMode.HALF_DOWN);
        String format1 = percentFmt.format(new BigDecimal("0.123456"));
        System.out.println(format1);//12.35%

        percentFmt.setMaximumFractionDigits(4);
        percentFmt.setMinimumFractionDigits(4);
        BigDecimal b1 = new BigDecimal("3");
        BigDecimal b2 = new BigDecimal("7");
        BigDecimal r1 = b1.divide(b2, 6, BigDecimal.ROUND_HALF_UP);
        System.out.println(percentFmt.format(r1));//60.0000%
    }

    /**
     * integer 整数
     */
    @Test
    public void integer() {
        NumberFormat integerFmt = NumberFormat.getIntegerInstance();
        String format2 = integerFmt.format(123456);
        System.out.println(format2);//123,456
    }

    @Test
    public void f3() {
        NumberFormat format = NumberFormat.getNumberInstance();
        format.setMaximumFractionDigits(2);
        //1,234.56
        String format2 = format.format(123456 / 100f);
        System.out.println(format2);//
    }
}
